'use client';

import { useRef, useEffect, useState, memo } from 'react';
import Image from 'next/image';
import noVideo from '@/img/wms/noVideo.png';
import styles from '../../pages.module.scss';

// 插件地址
const palyPath = `${process.env.NEXT_PUBLIC_OSS_URL}/hk/webVideoCtrl.js`;
const wsPath = process.env.NEXT_PUBLIC_WSS_URL;

let WebVideoCtrl: any = null;

const Hkplayer = (props: {
  visible: boolean;
  imageUrl: string;
  warehouseMontiorInfo: any;
}) => {
  const [hasVideo, setHasVideo] = useState(false);
  const [videoVisible, setVideoVisible] = useState(false);
  const initialized = useRef(false);

  let deplayTimer: any = null;

  const delayHandler = (cb: Function, time?: number) => {
    if (deplayTimer) {
      clearTimeout(deplayTimer);
    }
    deplayTimer = setTimeout(() => {
      cb();
    }, time || 3000);
  };

  const extractPort = (url: string) => {
    const firstColonIndex = url.indexOf(':');
    const secondColonIndex = url.indexOf(':', firstColonIndex + 1);

    if (secondColonIndex !== -1) {
      return url.substring(secondColonIndex + 1);
    }
    return null;
  };

  const initPlus = async () => {
    // 初始化插件参数及插入插件
    WebVideoCtrl.I_InitPlugin({
      bWndFull: false, //是否支持单窗口双击全屏，默认支持 true:支持 false:不支持
      iWndowType: 1,
      cbInitPluginComplete: function () {
        WebVideoCtrl.I_InsertOBJECTPlugin('HkDiv').then(
          async () => {
            const {
              monitorServerAddr,
              monitorServerAccount,
              monitorServerPassword,
            } = props.warehouseMontiorInfo;
            const domain = monitorServerAddr?.match(/\/\/(.*?):/)
              ? monitorServerAddr?.match(/\/\/(.*?):/)?.[1]
              : '';

            const port = extractPort(monitorServerAddr || '');
            WebVideoCtrl.I_Login(
              domain,
              1,
              port,
              monitorServerAccount,
              monitorServerPassword,
              {
                timeout: 3000,
                async: false,
                success: function () {
                  //开始播放
                  palyVideo();
                },
                error: function () {
                  delayHandler(initPlus);
                },
              },
            );
            // 检查插件是否最新
            WebVideoCtrl.I_CheckPluginVersion().then((bFlag: boolean) => {
              if (bFlag) {
                alert(
                  '检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！',
                );
              }
            });
          },
          () => {
            alert(
              '插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！',
            );
          },
        );
      },
    });
  };

  const palyVideo = () => {
    //开始播放
    WebVideoCtrl.I_StartRealPlay('video.zmetaport.com_17719', {
      iStreamType: 1,
      iChannelID: '7',
      bZeroChannel: false,
      success: function () {
        setHasVideo(true);
      },
      error: function () {
        setHasVideo(false);
        // retry
        delayHandler(palyVideo);
      },
    });
  };

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;
    const script = document.createElement('script');
    script.src = palyPath;
    script.onload = () => {
      WebVideoCtrl = (window as any).WebVideoCtrl;
      // 检查插件是否安装视频插件
      let iRet = WebVideoCtrl.I_CheckPluginInstall();
      if (-1 === iRet) {
        alert('您还未安装过插件，双击开发包目录里的WebComponentsKit.exe安装！');
        return;
      }
      delayHandler(initPlus, 1300);
    };
    script.onerror = (err) => {
      console.log('error', err);
    };
    document.body.appendChild(script);
  }, []);

  const timer = useRef<any>();
  const showTimer = useRef<any>();
  const pageTimer = useRef<any>();
  const visibleRef = useRef(false);

  useEffect(() => {
    if (!WebVideoCtrl) return;
    visibleRef.current = props.visible;
    if (props.visible) {
      timer.current = setTimeout(() => {
        showTimer.current = setTimeout(() => {
          WebVideoCtrl?.I_ShowWnd();
        }, 0);
        setVideoVisible(true);
      }, 1300);
    } else {
      WebVideoCtrl?.I_HideWnd();
      setVideoVisible(false);
    }

    const handlePlayerVisible = (event: any) => {
      if (event.data === 'hide') {
        WebVideoCtrl?.I_HideWnd();
      } else if (event.data === 'show') {
        pageTimer.current = setTimeout(() => {
          if (visibleRef.current) {
            WebVideoCtrl?.I_ShowWnd();
          }
        }, 600);
      }
    };

    window.addEventListener('message', function (event) {
      handlePlayerVisible(event);
    });

    return () => {
      clearInterval(timer.current);
      clearTimeout(showTimer.current);
      window.removeEventListener('message', handlePlayerVisible);
    };
  }, [props.visible]);

  return (
    <div className={styles.playerBox}>
      <div id="HkDiv" className={styles.playerBox}></div>
      {!hasVideo && (
        <Image
          src={noVideo}
          style={{
            position: 'absolute',
            width: '100%',
            height: 425,
            borderRadius: 10,
            left: 0,
            top: 0,
          }}
          alt="noVideo"
        />
      )}
      {!videoVisible && (
        <Image
          src={props.imageUrl}
          width={705}
          height={425}
          style={{
            position: 'absolute',
            width: 705,
            height: 425,
            borderRadius: 10,
            left: 0,
            top: 0,
          }}
          alt="noVideo"
        />
      )}
    </div>
  );
};

export default memo(Hkplayer);
